"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { DeliveryOption } from "@/components/delivery-option"
import { OrderSummary } from "@/components/order-summary"
import { ShareModal } from "@/components/share-modal"
import { ArrowLeft, Share2, CheckCircle, Home } from "lucide-react"
import type { CartItem } from "@/types"

interface OrderData {
  items: CartItem[]
  total: number
  itemCount: number
  timestamp: string
}

export default function OrderPage() {
  const router = useRouter()
  const [orderData, setOrderData] = useState<OrderData | null>(null)
  const [deliveryMethod, setDeliveryMethod] = useState<"pickup" | "delivery">("pickup")
  const [showShareModal, setShowShareModal] = useState(false)

  const deliveryFee = deliveryMethod === "delivery" ? 1.0 : 0
  const finalTotal = (orderData?.total || 0) + deliveryFee

  useEffect(() => {
    const savedOrder = localStorage.getItem("currentOrder")
    if (savedOrder) {
      try {
        setOrderData(JSON.parse(savedOrder))
      } catch (error) {
        console.error("Failed to load order data:", error)
        router.push("/")
      }
    } else {
      router.push("/")
    }
  }, [router])

  const handleBack = () => {
    router.push("/")
  }

  const handleShare = () => {
    setShowShareModal(true)
  }

  const handleNewOrder = () => {
    // 清除当前订单数据
    localStorage.removeItem("currentOrder")
    router.push("/")
  }

  if (!orderData) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <div className="text-center">
          <div className="text-4xl mb-4">⏳</div>
          <p className="text-muted-foreground">加载订单信息中...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-background pb-32">
      <header className="sticky top-0 z-10 bg-card border-b border-border">
        <div className="flex items-center gap-3 px-4 py-3">
          <Button variant="ghost" size="sm" onClick={handleBack} className="p-2">
            <ArrowLeft className="h-4 w-4" />
          </Button>
          <h1 className="text-lg font-semibold">订单确认</h1>
        </div>
      </header>

      <div className="p-4 space-y-4">
        {/* 订单状态 */}
        <Card className="bg-green-50 dark:bg-green-950/20 border-green-200 dark:border-green-800">
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <CheckCircle className="h-6 w-6 text-green-600 dark:text-green-400" />
              <div>
                <h3 className="font-semibold text-green-800 dark:text-green-200">订单提交成功</h3>
                <p className="text-sm text-green-600 dark:text-green-300">订单号：{orderData.timestamp.slice(-8)}</p>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 配送方式选择 */}
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-base">选择配送方式</CardTitle>
          </CardHeader>
          <CardContent className="space-y-3">
            <DeliveryOption
              type="pickup"
              selected={deliveryMethod === "pickup"}
              onSelect={() => setDeliveryMethod("pickup")}
              fee={0}
            />
            <DeliveryOption
              type="delivery"
              selected={deliveryMethod === "delivery"}
              onSelect={() => setDeliveryMethod("delivery")}
              fee={1.0}
            />
          </CardContent>
        </Card>

        {/* 订单摘要 */}
        <OrderSummary items={orderData.items} subtotal={orderData.total} deliveryFee={deliveryFee} total={finalTotal} />

        {/* 订单信息 */}
        <Card>
          <CardContent className="p-4">
            <div className="space-y-2 text-sm">
              <div className="flex justify-between">
                <span className="text-muted-foreground">下单时间</span>
                <span>{new Date(orderData.timestamp).toLocaleString("zh-CN")}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted-foreground">商品数量</span>
                <span>{orderData.itemCount} 件</span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted-foreground">订单状态</span>
                <span className="text-primary font-medium">待确认</span>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 温馨提示 */}
        <Card className="bg-blue-50 dark:bg-blue-950/20 border-blue-200 dark:border-blue-800">
          <CardContent className="p-4">
            <h3 className="font-medium text-blue-800 dark:text-blue-200 mb-2">温馨提示</h3>
            <ul className="text-sm text-blue-600 dark:text-blue-300 space-y-1">
              <li>• 请将订单信息转发给商家确认</li>
              <li>• 制作时间约 5-10 分钟</li>
              <li>• 如选择送货上门，请保持手机畅通</li>
              <li>• 如有问题请及时联系商家</li>
            </ul>
          </CardContent>
        </Card>
      </div>

      {/* Fixed Bottom Buttons */}
      <div className="fixed bottom-0 left-0 right-0 bg-card border-t border-border p-4">
        <div className="flex gap-3">
          <Button variant="outline" size="lg" className="flex-1 bg-transparent" onClick={handleNewOrder}>
            <Home className="h-4 w-4 mr-2" />
            再来一单
          </Button>
          <Button size="lg" className="flex-1" onClick={handleShare}>
            <Share2 className="h-4 w-4 mr-2" />
            转发给商家
          </Button>
        </div>
      </div>

      {/* Share Modal */}
      {orderData && (
        <ShareModal
          isOpen={showShareModal}
          onClose={() => setShowShareModal(false)}
          orderData={orderData}
          deliveryMethod={deliveryMethod}
          deliveryFee={deliveryFee}
          finalTotal={finalTotal}
        />
      )}
    </div>
  )
}
